if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lua5.3/lua.h")
  find_package(PkgConfig)
  if(PkgConfig_FOUND)
    foreach(pkg luajit lua lua53 lua52 lua51)
      pkg_check_modules(LUA ${pkg})
      if(LUA_FOUND)
	break()
      endif()
    endforeach()
  endif()
  if(LUA_FOUND)
    include_directories(${LUA_INCLUDE_DIRS})
  else()
    message(FATAL_ERROR "Lua not found, consider using `bash travis-install.sh` to download.")
  endif()
else()
  message(STATUS "Using in-tree lua source")
  include_directories(thirdparty/lua5.3)
  aux_source_directory(thirdparty/lua5.3 LUA_SRC)
  add_definitions(-DLUA_COMPAT_5_2)
  if(WIN32)
    set_property(SOURCE ${LUA_SRC} PROPERTY COMPILE_DEFINITIONS LUA_BUILD_AS_DLL)
  else()
    set_property(SOURCE ${LUA_SRC} PROPERTY COMPILE_DEFINITIONS LUA_USE_POSIX;LUA_USE_DLOPEN)
    execute_process(
      COMMAND ${CMAKE_C_COMPILER} -print-multiarch
      OUTPUT_VARIABLE multiarch
      ERROR_QUIET)
    if(multiarch)
      string(REGEX REPLACE "[\r\n]" "" multiarch ${multiarch})
      add_definitions(-DLUA_MULTIARCH=\"${multiarch}\")
      message(STATUS "with multiarch: ${multiarch}")
    endif()
  endif()
endif()

aux_source_directory(src RIME_LUA_SRC)
aux_source_directory(src/lib RIME_LUA_LIB_SRC)

add_library(rime-lua-objs OBJECT ${RIME_LUA_SRC} ${RIME_LUA_LIB_SRC} ${LUA_SRC})
if(BUILD_SHARED_LIBS)
  set_target_properties(rime-lua-objs PROPERTIES POSITION_INDEPENDENT_CODE ON)
endif()

set(plugin_name "rime-lua" PARENT_SCOPE)
set(plugin_objs $<TARGET_OBJECTS:rime-lua-objs> PARENT_SCOPE)
set(plugin_deps ${LUA_LIBRARIES} PARENT_SCOPE)
set(plugin_modules "lua" PARENT_SCOPE)
